package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"prod-cat-mgr/cache"
	"prod-cat-mgr/model"
	"prod-cat-mgr/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "没有此用户",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "没有此用户",
		})
		return
	}
	redis_key := "login_" + username
	errCont, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCont >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,等入失败",
		})
		return
	}
	if user.Password != pkg.M5str1(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCont == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var shop []model.Shop

	redis_key := "list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&shop)

		jsonData, _ := json.Marshal(&shop)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}
	var count int64
	model.DB.Model(&model.Shop{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  shop,
		"count": count,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var shop []model.Shop

	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).Find(&shop)

		jsonData, _ := json.Marshal(&shop)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": shop,
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	price, _ := strconv.Atoi(c.PostForm("price"))
	if title == "" || comment == "" || price == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不为空",
		})
		data := model.Shop{
			Title:   title,
			Comment: comment,
			Price:   price,
		}
		model.DB.Create(&data)
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
	}
}
